<template>
  <transition name="nou-toast-fade" @after-leave="handleAfterLeave">
    <div
      v-show="show"
      class="nou-toast"
      :class="{ danger: type === 'danger' }"
      :style="style"
    >
      {{ text }}
    </div>
  </transition>
</template>

<script>
export default {
  name: "NouToast",
  computed: {
    style() {
      return {
        top: `${this.top}px`,
      };
    },
  },
  data() {
    return {
      text: "",
      duration: 3000,
      uid: "",
      onClose: null,
      timer: null,
      show: false,
      top: 20,
      id: "",
      type: "primary", // primary/danger
    };
  },
  methods: {
    resetTimer() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        this.closeMessage();
      }, this.duration);
    },
    closeMessage() {
      if (this.onClose) {
        this.onClose();
      }
      this.handleClose();
      this.show = false;
    },
    handleAfterLeave() {
      this.$el.parentNode.removeChild(this.$el);
      this.$destroy();
    },
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
  mounted() {
    this.show = true;
    this.$nextTick(() => {
      this.resetTimer();
    });
  },
};
</script>

<style lang="scss" scoped>
.nou-toast {
  box-sizing: border-box;
  opacity: 1;
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  height: 42px;
  line-height: 42px;
  background: var(--card);
  color: var(--color);
  padding: 0 20px;
  min-width: 276px;
  text-align: center;
  transition: top 0.3s ease;
  border-radius: 5px;
  z-index: 99999;

  font-size: 14px;
  font-family: "Roboto Medium";
  font-weight: 400;

  &.danger {
    background: #ff0000;
    color: #fff;
  }
}

.nou-toast-fade-enter,
.nou-toast-fade-leave-active {
  opacity: 0;
  transform: translate(-50%, -100%);
}

.nou-toast-fade-enter-active,
.nou-toast-fade-leave-active {
  transition: all 0.3s ease;
}
</style>
